import {
  Button,
  Card,
  Col,
  Form,
  Input,
  message,
  Popconfirm,
  Row,
  Spin,
  Tag,
  Typography,
} from 'antd';
import React, { useCallback, useState } from 'react';
import { useAntdTable, useBoolean } from 'ahooks';
import request from '@/utils/request';
import { GlobalFormLayout } from '@/layouts/Form';
import Space from '@/components/Space';
import SlickTable from '@/components/SlickTable';

const { Text } = Typography;

function getTableData({ current, pageSize, processName, processCode }) {
  return request.post('/processCache/page', {
    data: {
      current,
      pageSize,
      processName,
      processCode,
    },
  });
}

const CacheStatusTagMap = {
  0: <span className="text-gray">未缓存</span>,
  1: <span className="text-success">已缓存</span>,
  2: <span className="text-danger">缓存序列化异常</span>,
  3: <span className="text-warning">缓存不一致</span>,
};

function ProcessCacheManager({ form }) {
  const { getFieldDecorator, getFieldsValue, resetFields } = form;
  const [loading, { setFalse: stopLoading, setTrue: startLoading }] = useBoolean(false);
  const [refreshFlag, { toggle }] = useBoolean(false);

  const {
    tableProps: { pagination, ...restTableProps },
  } = useAntdTable(
    query => {
      return getTableData({ ...query, ...getFieldsValue() });
    },
    {
      defaultPageSize: 10,
      refreshDeps: [refreshFlag],
    }
  );

  const refresh = useCallback(() => {
    toggle();
  }, [toggle]);

  /**
   * 刷新全部缓存
   */
  const reloadAllCache = () => {
    startLoading();
    request
      .post('/processCache/reloadAll')
      .then(() => {
        message.success('刷新成功');
        refresh();
      })
      .finally(() => stopLoading());
  };

  const clearAllCache = () => {
    startLoading();
    request
      .post('/processCache/clearAll')
      .then(() => {
        message.success('清除成功');
        refresh();
      })
      .finally(() => stopLoading());
  };

  /**
   * 刷新单个缓存
   */
  const reloadCache = useCallback(
    processCode => {
      startLoading();
      request
        .post(`/processCache/reloadOne?processCode=${processCode}`)
        .then(() => {
          message.success('刷新成功');
          refresh();
        })
        .finally(() => stopLoading());
    },
    [refresh, startLoading, stopLoading]
  );

  /**
   * 清除单个缓存
   */
  function clearCache(processCode) {
    startLoading();
    request
      .post(`/processCache/clearOne?processCode=${processCode}`)
      .then(() => refresh())
      .finally(() => stopLoading());
  }

  const columns = [
    {
      title: '流程名称',
      dataIndex: 'processName',
    },
    {
      title: '流程编码',
      dataIndex: 'processCode',
    },
    {
      title: '缓存Key值',
      dataIndex: 'cacheKey',
      render: text => <Text copyable>{text}</Text>,
    },
    {
      title: '数据库当前生效版本',
      dataIndex: 'dbVersionNumbers',
      render: text => text.join(', '),
    },
    {
      title: '缓存中的版本',
      dataIndex: 'cacheVersionNumber',
    },
    {
      title: '缓存状态',
      dataIndex: 'status',
      render: status => CacheStatusTagMap[status],
    },
    {
      title: '缓存操作',
      render: (_text, record) => {
        return (
          <Space>
            <Button
              type="primary"
              onClick={() => {
                if (record.dbVersionNumbers.length === 0) {
                  message.error('数据库无当前生效版本，不允许刷新缓存');
                  return;
                }
                if (record.dbVersionNumbers.length > 1) {
                  message.error('存在多个同时生效的数据库版本，不允许刷新缓存');
                  return;
                }
                reloadCache(record.processCode);
              }}
            >
              刷新缓存
            </Button>
            <Popconfirm
              title="清除缓存会导致HTTP数据源失效，请谨慎操作"
              onConfirm={() => clearCache(record.processCode)}
            >
              <Button type="danger">清除缓存</Button>
            </Popconfirm>

            {/* <Button type="primary" ghost>
              缓存核查
            </Button> */}
          </Space>
        );
      },
    },
  ];

  return (
    <Card className="cute" bodyStyle={{ padding: '32px' }} title="流程缓存管理">
      <Form {...GlobalFormLayout} style={{ marginBottom: '16px' }}>
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item label="流程名称">
              {getFieldDecorator('processName')(
                <Input onPressEnter={refresh} placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item label="流程编码">
              {getFieldDecorator('processCode')(
                <Input onPressEnter={refresh} placeholder="请输入" />
              )}
            </Form.Item>
          </Col>
          <Col span={6}>
            <Space>
              <Button type="primary" onClick={refresh}>
                查询
              </Button>
              <Button type="default" onClick={() => resetFields()}>
                重置
              </Button>
              <Button type="primary" onClick={reloadAllCache} loading={loading}>
                刷新全部缓存
              </Button>

              {/* <Popconfirm
                title="清除缓存会导致HTTP数据源失效，请谨慎操作"
                onConfirm={clearAllCache}
              >
                <Button type="danger" loading={loading}>
                  清除全部缓存
                </Button>
              </Popconfirm> */}
            </Space>
          </Col>
        </Row>
      </Form>
      <Row gutter={16}>
        <Spin spinning={loading}>
          <SlickTable
            rowKey="versionId"
            columns={columns}
            data={{ pagination }}
            {...restTableProps}
          />
        </Spin>
      </Row>
    </Card>
  );
}

export default Form.create()(ProcessCacheManager);
